package com.mgq.java8.lambda;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.function.Function;

/**
 * <b>功能：</b>环绕执行<br>
 * <b>Copyright mgq</b>
 * <li>版本&nbsp;&nbsp;&nbsp;&nbsp;修改日期&nbsp;&nbsp;&nbsp;&nbsp;部　　门&nbsp;&nbsp;&nbsp;&nbsp;作　者&nbsp;&nbsp;&nbsp;&nbsp;变更内容</li><hr>
 * <li>v1.0&nbsp;&nbsp;&nbsp;&nbsp;20220412&nbsp;&nbsp;营业后台&nbsp;&nbsp;&nbsp;&nbsp;马广奇&nbsp;&nbsp;&nbsp;&nbsp;创建类</li>
 * <br><br>
 * --------------------
 * <p>
 * 初始化
 * --------------------
 * 执行(读一行, 读2行......) 行为参数化,环绕执行
 * --------------------
 * 清理
 * ---------------------
 *
 * @author 马广奇
 * @version 2022-04-12 20:14
 */
public class ExecuteAround {
    public static void process(BufferedReader reader) {

    }

    /**
     * 第一版, 读取文件,返回第一行
     */
    public static String processFile() throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader("Apple.java"))) {
            return reader.readLine();
        }
    }

    /**
     * 读取文件,返回2行
     */
    public static String processFileTwoLine() throws IOException {
        try (BufferedReader reader = new BufferedReader(new FileReader("Apple.java"))) {
            return reader.readLine();
        }
    }

    /**
     * 第二版,行为参数化
     */
    public static String processFileVersion2(Function<BufferedReader, String> function) throws IOException {

        try (BufferedReader reader = new BufferedReader(new FileReader("Apple.java"))) {
            return function.apply(reader);
        }
    }

    public static void main(String[] args) throws IOException {
        //调用第二版
        processFileVersion2(reader -> {
                    try {
                        return reader.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
        );
        //行为参数化,返回2行
        processFileVersion2(reader -> {
                    try {
                        return reader.readLine()+reader.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }
        );
    }
}
